import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'other_profile_page_controller.dart';
import '../../function/model/post_model.dart';
import '../../function/utils/my_common.dart';

/// 他人个人资料页面组件
class OtherProfilePage extends GetView<OtherProfilePageController> {
  const OtherProfilePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/communal_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Obx(() {
            if (controller.targetUser == null) {
              return _buildErrorView();
            } else {
              return _buildProfileView();
            }
          }),
        ),
      ),
    );
  }

  /// 构建错误视图
  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64.sp,
            color: MyCommonUtils.white.withOpacity(0.7),
          ),
          SizedBox(height: 16.h),
          Text(
            'User not found',
            style: TextStyle(
              fontSize: 18.sp,
              color: MyCommonUtils.white.withOpacity(0.7),
            ),
          ),
          SizedBox(height: 24.h),
          ElevatedButton(
            onPressed: controller.goBack,
            style: ElevatedButton.styleFrom(
              backgroundColor: MyCommonUtils.green,
              foregroundColor: Colors.white,
            ),
            child: Text('Go Back'),
          ),
        ],
      ),
    );
  }

  /// 构建个人资料视图
  Widget _buildProfileView() {
    return Column(
      children: [
        // 顶部栏
        _buildTopBar(),

        // 可滚动的内容区域
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              children: [
                // 用户信息区域
                _buildUserInfoSection(),

                // 聊天和关注按钮区域
                _buildActionButtonsSection(),

                // 统计信息
                _buildStatsSection(),

                // 标签页
                _buildTabSection(),

                // 时间线内容
                _buildTimelineContent(),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建顶部栏
  Widget _buildTopBar() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        // 返回按钮
        Icon(
          Icons.arrow_back_ios,
          color: MyCommonUtils.white,
          size: 20.sp,
        ).padding(all: 8).inkWell(onTap: controller.goBack, borderRadius: 20.r),

        // 举报按钮
        Image.asset('assets/images/report.png', width: 24.w, height: 24.w)
            .padding(all: 8)
            .inkWell(onTap: controller.reportUser, borderRadius: 12.r),
      ],
    ).padding(horizontal: 20.w, vertical: 16.h);
  }

  /// 构建用户信息区域
  Widget _buildUserInfoSection() {
    final user = controller.targetUser!;

    return Column(
      children: [
        // 用户头像
        CircleAvatar(radius: 50.w, backgroundImage: AssetImage(user.avatar)),

        SizedBox(height: 16.h),

        // 用户名
        Text(
          user.nickname.isNotEmpty ? user.nickname : user.username,
        ).fontSize(24.sp).bold().textColor(MyCommonUtils.white),

        SizedBox(height: 8.h),

        // 用户签名
        Text(
              user.signature.isNotEmpty
                  ? user.signature
                  : 'Plant lover and nature enthusiast',
            )
            .fontSize(14.sp)
            .textColor(MyCommonUtils.white.withOpacity(0.8))
            .textAlignment(TextAlign.center),
      ],
    ).padding(horizontal: 20.w, vertical: 20.h);
  }

  /// 构建操作按钮区域
  Widget _buildActionButtonsSection() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 聊天按钮
        Image.asset('assets/images/chat_button.png', width: 24.w, height: 24.w)
            .padding(horizontal: 16.w, vertical: 8.h)
            .card(
              color: MyCommonUtils.blue,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(25.r),
              ),
            )
            .inkWell(onTap: controller.startChat, borderRadius: 25.r),

        SizedBox(width: 16.w),

        // 关注按钮
        Obx(() {
          final isFollowing = controller.isFollowing;
          return (isFollowing
                  ? Image.asset(
                    'assets/images/followed.png',
                    width: 24.w,
                    height: 24.w,
                  )
                  : Image.asset(
                    'assets/images/follow.png',
                    width: 24.w,
                    height: 24.w,
                  ))
              .padding(horizontal: 16.w, vertical: 8.h)
              .card(
                color: isFollowing ? MyCommonUtils.white : MyCommonUtils.blue,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.r),
                ),
              )
              .inkWell(onTap: controller.toggleFollow, borderRadius: 25.r);
        }),
      ],
    ).padding(vertical: 10.h);
  }

  /// 构建统计信息区域
  Widget _buildStatsSection() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        _buildStatItem('Following', controller.followingCount),
        _buildStatDivider(),
        _buildStatItem('Followers', controller.followersCount),
        _buildStatDivider(),
        _buildStatItem('Likes', controller.likesReceivedCount),
      ],
    ).padding(horizontal: 10.w);
  }

  /// 构建统计项
  Widget _buildStatItem(String label, int count) {
    return Column(
      children: [
        Text(
          count.toString(),
        ).fontSize(20.sp).bold().textColor(MyCommonUtils.white),
        SizedBox(height: 4.h),
        Text(
          label,
        ).fontSize(12.sp).textColor(MyCommonUtils.white.withOpacity(0.8)),
      ],
    );
  }

  /// 构建统计项分隔符
  Widget _buildStatDivider() {
    return Container(
      width: 1.w,
      height: 40.h,
      color: Colors.white.withOpacity(0.3),
    );
  }

  /// 构建标签页区域
  Widget _buildTabSection() {
    return Row(
          children: [
            Expanded(child: _buildTabButton('Posts', 0)),
            Expanded(child: _buildTabButton('Favorites', 1)),
          ],
        )
        .card(
          color: Colors.white.withValues(alpha: 0.2),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(100.r),
          ),
        )
        .padding(horizontal: 20.w, vertical: 20.h);
  }

  /// 构建标签按钮
  Widget _buildTabButton(String label, int index) {
    return Obx(() {
      final isSelected = controller.currentTabIndex.value == index;
      return Text(label)
          .fontSize(24.sp)
          .fontWeight(isSelected ? FontWeight.w700 : FontWeight.w400)
          .textColor(Colors.white)
          .textAlignment(TextAlign.center)
          .padding(vertical: 10.h)
          .card(
            color:
                isSelected
                    ? MyCommonUtils
                        .blue // 使用渐变背景
                    : Colors.white.withValues(alpha: 0.2),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(100.r),
            ),
          )
          .inkWell(onTap: () => controller.switchTab(index));
    });
  }

  /// 构建时间线内容
  Widget _buildTimelineContent() {
    return Obx(() {
      if (controller.currentTabIndex.value == 0) {
        return _buildPostsTimeline();
      } else {
        return _buildFavoritesTimeline();
      }
    });
  }

  /// 构建帖子时间线
  Widget _buildPostsTimeline() {
    final postsByDate = controller.userPostsByDate;

    if (postsByDate.isEmpty) {
      return Text('No posts yet')
          .fontSize(16.sp)
          .textColor(MyCommonUtils.white.withOpacity(0.7))
          .center()
          .padding(all: 200.h);
    }

    return _buildConnectedTimeline(postsByDate)
        .card(
          color: Colors.white.withValues(alpha: 0.12),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16.r),
            side: BorderSide(color: Colors.white.withOpacity(0.2), width: 1),
          ),
        )
        .padding(horizontal: 20.w, vertical: 20.h);
  }

  /// 构建收藏时间线
  Widget _buildFavoritesTimeline() {
    final postsByDate = controller.userLikedPostsByDate;

    if (postsByDate.isEmpty) {
      return Text('No favorites yet')
          .fontSize(16.sp)
          .textColor(MyCommonUtils.white.withOpacity(0.7))
          .center()
          .padding(all: 200.h);
    }

    return _buildConnectedTimeline(postsByDate)
        .card(
          color: Colors.white.withValues(alpha: 0.12),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16.r),
            side: BorderSide(color: Colors.white.withOpacity(0.2), width: 1),
          ),
        )
        .padding(horizontal: 20.w, vertical: 20.h);
  }

  /// 构建简化的时间线
  Widget _buildConnectedTimeline(Map<String, List<PostModel>> postsByDate) {
    return Padding(
      padding: EdgeInsets.all(12.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 按日期分组显示内容
          ...postsByDate.entries.toList().asMap().entries.map((dateGroupEntry) {
            final dateEntry = dateGroupEntry.value;
            final date = dateEntry.key;
            final posts = dateEntry.value;

            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 日期标题
                Text(date)
                    .fontSize(18.sp)
                    .bold()
                    .textColor(MyCommonUtils.white)
                    .padding(bottom: 16.h),

                // 该日期的所有帖子
                ...posts
                    .map((post) => _buildTimelineItemContent(post))
                    .toList(),

                SizedBox(height: 24.h),
              ],
            );
          }).toList(),
        ],
      ),
    );
  }

  /// 构建时间线项目内容
  Widget _buildTimelineItemContent(PostModel post) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 时间显示区域
        Text(controller.formatTime(post.publishTime))
            .fontSize(12.sp)
            .textColor(MyCommonUtils.white.withOpacity(0.7))
            .fontWeight(FontWeight.w500)
            .padding(top: 2.h)
            .padding(right: 50.w),

        SizedBox(width: 12.w),

        // 帖子内容
        Expanded(child: _buildPostItem(post)),
      ],
    ).padding(bottom: 24.h);
  }

  /// 构建帖子项
  Widget _buildPostItem(PostModel post) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 帖子内容区域
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 帖子标题
            Text(post.title)
                .fontSize(18.sp)
                .bold()
                .textColor(MyCommonUtils.white)
                .padding(bottom: 12.h),

            // 帖子内容
            Text(post.content)
                .fontSize(15.sp)
                .textColor(MyCommonUtils.white.withOpacity(0.9))
                .padding(bottom: 16.h),

            // 帖子标签
            if (post.tags.isNotEmpty)
              Wrap(
                spacing: 8.w,
                runSpacing: 6.h,
                children:
                    post.tags.take(3).map((tag) {
                      return Text('# $tag')
                          .fontSize(12.sp)
                          .textColor(MyCommonUtils.white.withOpacity(0.8))
                          .fontWeight(FontWeight.w500)
                          .padding(horizontal: 12.w, vertical: 6.h)
                          .card(
                            color: MyCommonUtils.white.withOpacity(0.15),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(16.r),
                              side: BorderSide(
                                color: MyCommonUtils.white.withOpacity(0.3),
                                width: 1,
                              ),
                            ),
                          );
                    }).toList(),
              ).padding(bottom: 16.h),
          ],
        ),

        // 帖子图片/视频
        if (post.resourceType == ResourceType.image)
          _buildPostImage(post)
        else if (post.resourceType == ResourceType.video)
          _buildPostVideo(post),
      ],
    ).inkWell(onTap: () => controller.goToPostDetail(post));
  }

  /// 构建帖子图片
  Widget _buildPostImage(PostModel post) {
    return ClipRRect(
      borderRadius: BorderRadius.all(Radius.circular(16.r)),
      child: Image.asset(
        post.resourcePath,
        width: double.infinity,
        height: 220.h,
        fit: BoxFit.cover,
      ),
    );
  }

  /// 构建帖子视频
  Widget _buildPostVideo(PostModel post) {
    return GestureDetector(
      onTap: () => controller.playVideo(post),
      child: Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.all(Radius.circular(16.r)),
            child: Image.asset(
              post.coverImagePath ?? post.resourcePath,
              width: double.infinity,
              height: 220.h,
              fit: BoxFit.cover,
            ),
          ),
          // 播放按钮
          Positioned.fill(
            child: Center(
              child: Container(
                width: 70.w,
                height: 70.w,
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.7),
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.3),
                      blurRadius: 8,
                      spreadRadius: 2,
                    ),
                  ],
                ),
                child: Icon(
                  Icons.play_arrow,
                  color: MyCommonUtils.white,
                  size: 35.sp,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
